package com.mybatis.lo;

import com.mybatis.lo.builder.SqlSessionFactoryBuilder;
import com.mybatis.lo.config.Configuration;
import com.mybatis.lo.config.MappedStatement;
import com.mybatis.lo.dao.UserDao;
import com.mybatis.lo.dao.UserDaoImplWithMybatis;
import com.mybatis.lo.factory.SqlSessionFactory;
import com.mybatis.lo.io.ClassPathResources;
import com.mybatis.lo.po.User;
import com.mybatis.lo.sqlsession.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * 自己实现的mybatis-framework框架测试
 * @author zhangbh
 * 2023-06-21 07:59
 **/
public class UserDaoTestWithMybatis {


    SqlSession sqlSession;

    @Before
    public void loadConfig() {
        ClassPathResources classPathResources = new ClassPathResources();
        SqlSessionFactory factory = SqlSessionFactoryBuilder.build(classPathResources.getResourceAsStream("SqlMapConfig.xml"));
        sqlSession = factory.openSession();
    }


    @Test
    public void testQueryUserById() {
        UserDao userDao = new UserDaoImplWithMybatis(sqlSession);
        User user = userDao.queryUserById(1);
        System.out.println(user);
    }

    @Test
    public void testQueryUsersByUsername() {
        UserDao userDao = new UserDaoImplWithMybatis(sqlSession);
        List<User> users = userDao.queryUserByName("王五");
        System.out.println(users);
    }

    @Test
    public void testQueryUsers() {
        UserDao userDao = new UserDaoImplWithMybatis(sqlSession);
        User user = User.builder().id(1).username("王").build();
        List<User> users = userDao.queryUser(user);
        System.out.println(users);
    }

    /**
     * 验证一级缓存{@link com.mybatis.lo.executor.BaseExecutor#queryList(MappedStatement, Configuration, Object)}
     */
    @Test
    public void testQueryUsersFromCache() {
        UserDao userDao = new UserDaoImplWithMybatis(sqlSession);
        User user = User.builder().id(1).username("王").build();
        List<User> users = userDao.queryUser(user);
        System.out.println(users);
        // 验证缓存
        user = User.builder().id(1).username("王").build();
        users = userDao.queryUser(user);
        System.out.println(users);
    }
}
